package lims.tools;

import java.security.SecureRandom;

import javax.crypto.spec.DESKeySpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;

/**
 * DES加解密算法
 * @author gary
 */
public class DES{
	/**
	 * DES加密
	 * @param datasource 源数据
	 * @param password 密码，长度必须为8的倍数
	 * @return 加密结果
	 */
	public static byte[] encrypt(byte[] datasource, byte[] password) {
		try{
			SecureRandom random = new SecureRandom();
			DESKeySpec desKey = new DESKeySpec(password);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(desKey);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
			return cipher.doFinal(datasource);
		}catch(Throwable e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * DES解密
	 * @param src，源数据
	 * @param password 密码，长度必须为8的倍数
	 * @return 解密结果
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] src, byte[] password) throws Exception {
		SecureRandom random = new SecureRandom();
		DESKeySpec desKey = new DESKeySpec(password);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(desKey);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.DECRYPT_MODE, securekey, random);
		return cipher.doFinal(src);
	}
	
	
	public static void main(String[] args) throws Exception {
		String pwd="hello111";  
		
		String srcString="测试数据";
		byte[] encoded=encrypt(srcString.getBytes(),pwd.getBytes());
		byte[] decoded=decrypt(encoded,pwd.getBytes());
		System.out.println(new String(decoded,"utf8"));
	}

}
